package com.study.zookeeperAPI;


import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class FirstZookeeper {

    public ZooKeeper zooKeeper;

    private static CountDownLatch latch = new CountDownLatch(1);

    public static void main(String[] args) throws IOException, InterruptedException {

        System.out.println("hahfhahf");
        ZooKeeper zk = connectZookeeper();
        while (true){
            Thread.sleep(5000);
        }
    }


    //创建一个最基本的Zookeeper会话实力
    public static ZooKeeper connectZookeeper()throws IOException,InterruptedException {

        String connectStr = "127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2184";
        //每5s发送一次心跳
        int session_time = 5000;
        ZooKeeper zk = new ZooKeeper(connectStr, session_time, new Watcher() {
            public void process(WatchedEvent watchedEvent) {
                if(watchedEvent.getState() == Event.KeeperState.SyncConnected){
                    System.out.println("zookeeper connection ok……");
                    //释放阻塞
                    latch.countDown();
                }else if(watchedEvent.getState().equals(Event.KeeperState.Disconnected)) {
                    //这时收到断开连接的消息，这里其实无能无力，因为只是已经和zk断开连接了，只能等再次开启了
                    System.out.println("zk Disconnected");
                }else if(watchedEvent.getState().equals(Event.KeeperState.Expired)){
                    //这时收到这个信息，表示zk已经重新连接上了，但是会话丢失了，这时需要重新建立会话
                    System.out.println("zk Expired");
                }else if(watchedEvent.getState().equals(Event.KeeperState.AuthFailed)){
                    System.out.println("zk AuthFailed");
                }else{
                    System.out.println("else condition……" + watchedEvent.getType());
                }
            }
        });
        System.out.println("zk status=" + zk.getState());
        //阻塞，等待zk连接成功，或者5s超时，否则不能往下执行
        latch.await(5000, TimeUnit.MILLISECONDS);
        System.out.println("zk connection OK, lock release……");
        return zk;
    }

}
